package cloud.seri.iot.manager.service

import cloud.seri.iot.common.model.CreateProductDTO
import cloud.seri.iot.common.model.UpdateProductDTO
import cloud.seri.iot.manager.client.ProductManagerClient
import cloud.seri.iot.manager.domain.Product
import cloud.seri.iot.manager.repository.ProductRepository
import cloud.seri.iot.manager.service.dto.ProductDTO
import cloud.seri.iot.manager.service.example.ProductExample
import cloud.seri.iot.manager.service.example.exampleMatcher
import cloud.seri.iot.manager.service.mapper.ProductMapper
import com.aliyuncs.iot.model.v20180120.QueryProductResponse
import net.dreamlu.mica.core.result.R
import org.slf4j.LoggerFactory
import org.springframework.data.domain.*
import org.springframework.stereotype.Service

/**
 * Service Implementation for managing [Product].
 */
@Service
class ProductService(
    val productRepository: ProductRepository,
    val productMapper: ProductMapper,
    val productManagerClient: ProductManagerClient
)
{


    private val log = LoggerFactory.getLogger(ProductService::class.java)


//    @PostConstruct
//    fun initProductList()
//    {
//        productManagerClient.queryProductList(PageRequestDTO().apply {
//            currentPage = 1
//            pageSize = 50
//        })?.let { response ->
//            log.info(response.toString())
//            if (response.success)
//            {
//                val ps = response.data.list.map {
//                    Product(productKey = it.productKey,
//                        description = it.description,
//                        dataFormat = it.dataFormat,
//                        deviceType = it.nodeType,
//                        productName = it.productName)
//                        .apply { createdDate = Instant.ofEpochMilli(it.gmtCreate) }
//                }
//                productRepository.saveAll(ps)
//            }
//        }
//
//    }

    /**
     * Save a product.
     *
     * @param productDTO the entity to save.
     * @return the persisted entity.
     */
    fun save(productDTO: CreateProductDTO): R<ProductDTO>?
    {
        productManagerClient.createProduct(productDTO)?.let {
            return if (it.success)
            {
                var product = productMapper.createProductEntity(it.data)
                product = productRepository.save(product)
                R.success(productMapper.toDto(product))

            }
            else
            {
                R.fail(it.errorMessage)
            }
        }
        return null
    }

    fun update(productDTO: UpdateProductDTO): R<ProductDTO>?
    {
        val p = productRepository.findById(productDTO.productKey!!)
        if (!p.isPresent)
        {
            return R.fail("产品不存在")
        }
        else
        {
            var result = p.get()
            productManagerClient.updateProduct(productDTO)?.let { response ->
                return if (response.success)
                {
                    result.description = productDTO.description
                    result.productName = productDTO.productName
                    result = productRepository.save(result)
                    R.success(productMapper.toDto(result))
                }
                else
                {
                    R.fail(response.errorMessage)
                }
            }

        }
        return null
    }

    /**
     * Get all the products.
     *
     * @return the list of entities.
     */
    fun findAll(page: Pageable, criteria: ProductExample?): Page<ProductDTO>
    {
        log.debug("请求全部产品 $page $criteria")
        if (criteria.hashCode() > 0)
            productMapper.productExampleToEntity(criteria)?.let { product ->
                return productRepository.findAll(Example.of(product, product.exampleMatcher()), page).map { productMapper.toDto(it) }
            }
        return productRepository.findAll(page).map { productMapper.toDto(it) }
    }

    /**
     * Get one product by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
    fun findOne(id: String): QueryProductResponse?
    {
        log.debug("Request to get Product : {}", id)
        return productManagerClient.queryProduct(id)
//        return productRepository.findById(id)
//            .map(productMapper::toDto)
    }

    /**
     * Delete the product by id.
     *
     * @param id the id of the entity.
     */
    fun delete(id: String): R<Void>
    {
        log.debug("Request to delete Product : {}", id)

        productManagerClient.deleteProduct(id)?.let {
            return if (it.success)
            {
                productRepository.deleteById(id)
                R.success()
            }
            else
            {
                R.fail(it.errorMessage)
            }
        }
        return R.fail("删除失败")
    }

    fun queryProductList(): List<ProductDTO>
    {
        return productRepository.findAll(Sort(Sort.Direction.DESC,"createdDate")).map { productMapper.toDto(it) }
    }
}
